package com.zzptc.lzh.myapp4;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

import com.zzptc.lzh.myapp4.entity.Book;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    private Handler handler=new Handler(){//传送的师傅，我们只管放和取
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            Bitmap obj = (Bitmap) msg.obj;//取对象
            imageView.setImageBitmap(obj);
        }
    };
    private ImageView imageView;
    //int[] pics={R.mipmap.ic_launcher,R.mipmap.ic_launcher_round};
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();//实例化控件
        new Thread(new Runnable() {//new一个子线程
            @Override
            public void run() {
                initData();//实例化数据
                Log.d(TAG, "onCreate: "+Thread.currentThread().getName());
            }
        }).start();

        //Log.d(TAG, "onCreate: "+Thread.currentThread().getName());
        //new Book(1,pics[0],"java基础",100F);


    }
    public void initView(){
        imageView=findViewById(R.id.iv);
    }
    public void initData(){
        try {
            URL url=new URL("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604471345196&di=953521af9ffa024bccbedf8c47203864&imgtype=0&src=http%3A%2F%2Ffile02.16sucai.com%2Fd%2Ffile%2F2014%2F0829%2F372edfeb74c3119b666237bd4af92be5.jpg");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置访问方式get post
            conn.setRequestMethod("GET");
            //判断服务器的返回结果
            int code=conn.getResponseCode();
            if (code==200){
                InputStream inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                //往主线程里发消息，放对象
                Message message = handler.obtainMessage();
                message.obj=bitmap;
                handler.sendMessage(message);

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}